package com.yuanzhy.tools.commons.pool;

import org.apache.commons.pool2.impl.GenericKeyedObjectPool;
import org.apache.commons.pool2.impl.GenericKeyedObjectPoolConfig;

public class KeyedDemo {

    public static void main(String[] args) throws Exception {
        GenericKeyedObjectPoolConfig<ComplexObject> poolConfig = new GenericKeyedObjectPoolConfig<>();
        // 每个Key最大空闲实例数，空闲超过此值将会被销毁淘汰
        poolConfig.setMaxIdlePerKey(5);
        // 每个Key最小空闲实例数，对象池将至少保留2个空闲对象
        poolConfig.setMinIdlePerKey(2);
        // 其他设置基本同 GenericObjectPoolConfig
        // ... ...

        ComplexKeyedPooledObjectFactory objectFactory = new ComplexKeyedPooledObjectFactory();
        GenericKeyedObjectPool<MyKey, ComplexObject> objectPool = new GenericKeyedObjectPool<MyKey, ComplexObject>(objectFactory, poolConfig);
        // 申请对象
        MyKey myKey = new MyKey("root", "123456");
        ComplexObject obj1 = objectPool.borrowObject(myKey);
        System.out.println("第一次申请对象：" + obj1.getName());
        // returnObject应该放在finally中 避免业务异常没有归还对象，demo仅做示例
        objectPool.returnObject(myKey, obj1);
        // 申请对象， 由于之前归还了，借用的还是之前的对象
        ComplexObject obj2 = objectPool.borrowObject(myKey);
        System.out.println("第二次申请对象：" + obj2.getName());
        // 再次申请对象，由于之前没有归还，借用的是新创建的
        ComplexObject obj3 = objectPool.borrowObject(myKey);
        System.out.println("第三次申请对象：" + obj3.getName());

        objectPool.returnObject(myKey, obj2);
        objectPool.returnObject(myKey, obj3);
    }
}
